from flask import Flask, render_template, request
from mastodon import Mastodon
import sched, time

TOOTS_PER_DAY = 2

s = sched.scheduler(time.time, time.sleep)
toots_by_ip = {}

app = Flask(__name__)
mastodon = Mastodon(access_token="usercred.secret", api_base_url="https://cuties.social") # CHANGE THE URL HERE if you use a different instance

def reset_ratelimits():
    # Reset
    toots_by_ip = {}
    #Schedule next reset
    t = time.localtime(time.time()+86400+60) # One day from now plus a minute just in case it accidentaly runs shortly before midnight   
    due_next = time.mktime((t.tm_year, t.tm_mon, t.tm_mday, 0, 0, 0, t.tm_wday, t.tm_yday, t.tm_isdst)) # Midnight of the day of t
    s.enterabs(due_next, 1, reset_ratelimits)

def get_ratelimit(remote_addr):
    # Reset ratelimit if it is due
    s.run(blocking=False)

    # Determine ratelimit for this IP
    remaining_toots_today = TOOTS_PER_DAY
    if remote_addr in toots_by_ip:
        remaining_toots_today -= toots_by_ip[remote_addr]

    if remaining_toots_today < 0: #Should not happen
        remaining_toots_today = 0

    return remaining_toots_today

@app.route("/anontoots/")
def show_form():
    return render_template("form.html", ratelimit=get_ratelimit(request.remote_addr))

@app.route("/anontoots/submit/", methods = ["POST"])
def submit():
    ratelimit = get_ratelimit(request.remote_addr)
    if(ratelimit>0):
        message = request.form["message"]
        cw = request.form["cw"]
        if not cw:
            cw = "kein CW angegeben"
        if not message:
            return render_template("submitted.html", success = False, ratelimit_hit = False)
        mastodon.status_post(message, spoiler_text="Anonym eingereicht, " + cw)
        
        # Register toot for ratelimit count
        if request.remote_addr in toots_by_ip:
            toots_by_ip[request.remote_addr]+=1
        else:
            toots_by_ip[request.remote_addr]=1

        return render_template("submitted.html", success = True)
    else:
        return render_template("submitted.html", success = False, ratelimit_hit = True)
